import os
import json
import re
import random
import math
import time
import asyncio
import shutil
import datetime
import base64
from botpy import logging
from botpy.message import GroupMessage
from tools import send_message, read_time, txt_exist, txt_write, player_id, bag_add, player_read, player_write, player_number, bag_enough, bag_reduce, player_name, generate_code
from database_basic import create_database, game_update, game_day_update
from database_equipments import create_equipments
from database_evolution import create_evolution
from database_maps import create_maps
from database_monsters import create_monsters
from database_shops import create_shops
from database_skills import create_skills
from battle import attribute_count, team_create, team_join, team_leave, team_list, team_infor, battle_initialization, battle_view, battle_round
from action import move, equip, make_thing, resolve_thing, action_use, devide_attribute, shop_buy, shop_sell, daily_wish, worldtree_action, guild_shop, guild_shop_buy, help_resolve_thing
from list import my_bag, my_attribute, my_equip, my_skill, search_all, make_list, make_infor, my_job, my_task, my_evolute, work_player_list, my_board
from pet import get_pet, pet_information, pet_break
from botpy.types.message import MarkdownPayload, MessageMarkdownParams
from alchemy import do_alchemy, do_many_alchemy, help_do_alchemy
from forge import do_enchant, do_reinforce, help_do_enchant
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as mcolors
#from abyss import make_map

async def process_message_content(message) -> str:
    
    if hasattr(message.author, 'member_openid'):
        number = message.author.member_openid 
    elif hasattr(message.author, 'user_openid'):    
        number = message.author.user_openid
    uid = await player_id(number)
    message.content = message.content.strip()
    message.content = message.content.replace(' ', '')
    message.content = message.content.replace('/', '')
    if message.content == "初始化":
        if number != "71DFEA7BBB6DFB39E7C2B7ABB3ABDDB8":
            txt = "\n【没有足够的权限！】"
            await send_message(message, 0, 1, txt)
            return

        await create_database()
        await create_shops()
        await game_update()
        txt = f"初始化已完成！"
        await send_message(message, 0, 1, txt, None)
        return

    state = await txt_exist("player", "number", number, "状态")
    if_team = await txt_exist("player", "number", number, "队伍中")
    place_now = await txt_exist("player", "number", number, "地名")
    if message.content == "我":

        txt = number
        await send_message(message, 0, 1, txt)
        return

    if "测试" in message.content:
        
        if "木桩" in message.content:

            await battle_initialization("木桩", 28, message, "标准")
            return

        if "剑影1" in message.content:

            await battle_initialization("无名剑影", 30, message, "精明")
            return

        if number != "71DFEA7BBB6DFB39E7C2B7ABB3ABDDB8":
            txt = "\n【没有足够的权限！】"
            await send_message(message, 0, 1, txt)
            return

        if "绿史" in message.content:

            await battle_initialization("森林史莱姆", 10, message, "随机大")
            return

        if "黑史" in message.content:

            await battle_initialization("岩石史莱姆", 10, message, "随机大")
            return

        if "噶" in message.content:

            await battle_initialization("大学者[噶]", 25, message, "神圣")
            return

        if "猪" in message.content:

            await battle_initialization("刺毛猪", 30, message, "随机大")
            return

        if "拳" in message.content:

            await battle_initialization("狂拳·艾森", 25, message, "神力")
            return

        if "生成" in message.content:

            await make_map(message)
            return

    elif message.content == "测试":
        txt = "\n【诸神殿堂•生命女神】\n“我平等的爱惜每一个生灵。”\n◈[1] 学习 医者仁心\n  (需供奉[天空粉尘]×1)\n◈[2] 学习 圣者箴言\n  (需供奉[天空粉尘]×10)\n◈[0] 返回\n————————————\n发送[1][2][0]进行操作"
        await send_message(message, 0, 1, txt, "https://gss0.baidu.com/9fo3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/cb8065380cd791230d0a6aa2a8345982b3b7807a.jpg")
        return


    elif "全局搜索" in message.content:
        #if number != "71DFEA7BBB6DFB39E7C2B7ABB3ABDDB8":
        #    txt = "\n【没有足够的权限！】"
        #    await send_message(message, 0, 1, txt)
        #    return
        await search_all(message)
        return
    elif message.content == "行动":
        await txt_write("player", "number", number, "状态", "行动")
        txt = "\n【回到[行动]状态！】"
        await send_message(message, 0, 1, txt)
        return
    elif "命令" in message.content:

        if number != "71DFEA7BBB6DFB39E7C2B7ABB3ABDDB8":
            txt = "\n【没有足够的权限！】"
            await send_message(message, 0, 1, txt)
            return

        if "命令修复" in message.content:
            directory = "data/player/"
            for filename in os.listdir(directory):
                if filename.endswith(".txt"):
                    filepath = os.path.join(directory, filename)
                    with open(filepath, 'r') as f:
                        data = json.load(f)
                    if "进化" in data:
                        for item in data["进化"]:
                            if item["属性"] == "减伤":
                                item["属性"] = "物理减伤"
                            if item["属性"] == "魔防":
                                item["属性"] = "魔法减伤"
                        with open(filepath, 'w') as f:
                            json.dump(data, f, ensure_ascii=False, indent=4)
            txt = "\n【修复完成！】"
            await send_message(message, 0, 1, txt)
            return
        
        if "命令存档" in message.content or "命令保存" in message.content:
            now = datetime.datetime.now() + datetime.timedelta(hours=0)
            current_time = now.strftime("%Y-%m-%d %H:%M:%S")
            current_folder = os.path.dirname(os.path.abspath(__file__))
            source_folder = current_folder + "/data"
            destination_folder = current_folder + "/data备份/"
            shutil.copytree(source_folder, destination_folder + current_time)
            txt = "\n【当前保存成功！】"
            await send_message(message, 0, 1, txt)
            return

        if "命令检查属性" in message.content:
            txt = "\n检查结果如下："
            directory = "data/player/"
            for filename in os.listdir(directory):
                if filename.endswith(".txt"):
                    filepath = os.path.join(directory, filename)
                    with open(filepath, 'r') as f:
                        data = json.load(f)
                    add1 = data["力量"]["基础"] + data["智力"]["基础"] + data["体质"]["基础"] + data["敏捷"]["基础"] 
                    if add1 != 20:
                        txt += "\n【{}[id{}]】四维基础异常！".format(data["nickname"], data["id"])
                    add2 = data["力量"]["加点"] + data["智力"]["加点"] + data["体质"]["加点"] + data["敏捷"]["加点"] + data["属性点"]
                    if data["等级"] != add2:
                        txt += "\n【{}[id{}]】属性点异常！".format(data["nickname"], data["id"])
                    if data.get("灵阶", 1) == 3:
                        if len(data["进化"]) != int(int(data["等级"]) - 19):
                            txt += "\n【{}[id{}]】进化数量异常！".format(data["nickname"], data["id"])
            await send_message(message, 0, 1, txt)
            return

        if "命令重置加点" in message.content:
            directory = "data/player/"
            for filename in os.listdir(directory):
                if filename.endswith(".txt"):
                    filepath = os.path.join(directory, filename)
                    with open(filepath, 'r') as f:
                        data = json.load(f)
                    data["力量"]["加点"] = 0
                    data["智力"]["加点"] = 0
                    data["体质"]["加点"] = 0
                    data["敏捷"]["加点"] = 0
                    data["属性点"] = data["等级"] * 1
                    with open(filepath, 'w') as f:
                        json.dump(data, f, ensure_ascii=False, indent=4)
            txt = "\n【加点已重置！】"
            
            await send_message(message, 0, 1, txt)
            return

        if "命令重置体力" in message.content:
            await game_day_update()
            txt = "\n【体力已重置！】"
            await send_message(message, 0, 1, txt)
            return

        if "命令设置" in message.content:

            word = message.content.split("命令设置")[1]
            word1 = re.findall('[\u4e00-\u9fff]+', word)[0]
            word2 = re.findall('\d+', word)[0]
            with open(f"data/配置.txt", 'r') as f:
                data = json.load(f)
            if word1 in data:
                data[word1] = int(word2)
                with open("data/配置.txt", 'w') as f:
                    json.dump(data, f, ensure_ascii=False, indent=4)
                txt = "\n【已将{}修改为[{}]秒】".format(word1, word2)
            else:
                txt = "\n【设置错误！】"
            await send_message(message, 0, 1, txt)
            return

        if "命令获取宠物" in message.content:

            uid = await player_id(number)
            pet_name = message.content.split("命令获取宠物")[1]
            txt = await get_pet(uid, pet_name)
            txt = "\n" + txt
            await send_message(message, 0, 1, txt)
            return

        if "命令群发" in message.content:
            thing = message.content.split("命令群发")[1]
            if len(thing.split("*")) == 2:
                thing_name = thing.split("*")[0]
                thing_number = thing.split("*")[1]
            elif len(thing.split("*")) == 1:
                thing_name = thing.split("*")[0]
                thing_number = 1
            with open(f"data/player.txt", 'r') as f:
                player_list = json.load(f)
            for player_item in player_list:
                uid = player_item["id"]
                await bag_add(uid, thing_name, thing_number)
            txt = "\n【发放成功！】"
            await send_message(message, 0, 1, txt)
            return

        if "命令进化诅咒" in message.content:

            await jinhua_zuzhou()
            return

        if message.content == "命令行动":
            with open("data/player.txt", 'r') as f:
                data = json.load(f)
            for player in data:
                if player["状态"] != "打工":
                    player["状态"] = "行动"
            with open("data/player.txt", 'w') as f:
                json.dump(data, f, ensure_ascii=False, indent=4)
            txt = "\n【状态[行动]已完成！】"
            await send_message(message, 0, 1, txt)
            return
 
    elif "赠送" in message.content:
        if "额度" in message.content:
            my_limit = await player_read(number, "赠送限制")
            my_max = int(await player_read(number, "等级")) * 1000 + 0
            out_limit = my_limit["总额度"] + my_max
            in_limit = my_max - my_limit["总额度"]
            txt = "\n【当前额度为：】\n◈可赠送价值[{}]\n◈可接收价值[{}]".format(out_limit, in_limit)
            await send_message(message, 0, 1, txt)
            return
        uid = await player_id(number)
        word = message.content.split("赠送")[1]
        word_split = word.split("*")
        if len(word_split) != 3:
            txt = "\n【赠送格式错误！】\n◈示例：[赠送 ID*物品名*数量]"
            await send_message(message, 0, 1, txt)
            return
        else:
            give_number = word_split[0]
            thing_name = word_split[1]
            thing_number = word_split[2]
            if int(thing_number) <= 0:
                txt = "\n【赠送数量错误！】"
                await send_message(message, 0, 1, txt)
                return
            if await txt_exist("player", "number", give_number, "") == "不存在":
                txt = "\n【赠送对象不存在！】\n◈发送[我]查看ID"
                await send_message(message, 0, 1, txt)
                return
            give_uid = await player_id(give_number)
            with open(f"data/bag/{uid}.txt", 'r') as f:
                data = json.load(f)
            have_equip = False
            guanming = False
            if_enough = "不够"
            for item in data['背包']:
                item_name = item['名称'].split("+")[0]
                if item_name == thing_name:
                    if int(item['数量']) >= int(thing_number):
                        whole_equip_name = item['名称']
                        if_enough = "够了"
                        break

            if number == "71DFEA7BBB6DFB39E7C2B7ABB3ABDDB8":
                whole_equip_name = thing_name
                if_enough = "够了"
            if "不够" in if_enough:
                txt = "\n【你没有足够的[{}]！】".format(thing_name)
                await send_message(message, 0, 1, txt)
                return
            elif "够了" in if_enough:
                give_name = await player_name(give_uid)
                my_limit = await player_read(number, "赠送限制")
                my_max = int(await player_read(number, "等级")) * 1000 + 0
                you_limit = await player_read(give_number, "赠送限制")
                you_max = int(await player_read(give_number, "等级")) * 1000 + 0
                if my_limit["总额度"] < -my_max and number != "71DFEA7BBB6DFB39E7C2B7ABB3ABDDB8":
                    txt = "\n【赠送失败！】\n◈你已超过赠送额度！"
                    await send_message(message, 0, 1, txt)
                    return
                elif you_limit["总额度"] > you_max and number != "71DFEA7BBB6DFB39E7C2B7ABB3ABDDB8":
                    txt = "\n【赠送失败！】\n◈对方已超过接收额度！"
                    await send_message(message, 0, 1, txt)
                    return

                with open("data/赠送限制.txt", 'r') as f:
                    limit_data = json.load(f)
                if thing_name in limit_data:
                    thing_value = limit_data[thing_name]
                else:
                    if number != "71DFEA7BBB6DFB39E7C2B7ABB3ABDDB8":
                        txt = "\n【该物品不可转赠！】"
                        await send_message(message, 0, 1, txt)
                        return
                    else:
                        thing_value = 0
                all_value = int(thing_value) * int(thing_number)
                if my_limit["总额度"] - all_value < -my_max and int(thing_number) != 1:
                    txt = "\n【赠送失败！】\n◈请尝试分开赠送！"
                    await send_message(message, 0, 1, txt)
                    return
                my_limit["总额度"] = int(my_limit["总额度"]) - all_value
                you_limit ["总额度"] = int(you_limit["总额度"]) + all_value

                if number != "71DFEA7BBB6DFB39E7C2B7ABB3ABDDB8":
                    await bag_reduce(uid, whole_equip_name, thing_number)
                await player_write(number, "赠送限制", None, my_limit)
                await player_write(give_number, "赠送限制", None, you_limit)
                await bag_add(give_uid, whole_equip_name, thing_number)
                txt = "\n【赠送成功！】\n◈你赠送了[{}]\n➥【{}】 × {}".format(give_name, thing_name, thing_number)
                await send_message(message, 0, 1, txt)
                return

        




    elif message.content == "菜单":
        #params = [
        #    MessageMarkdownParams(key="title", values=["幻想次元"]),
        #    MessageMarkdownParams(key="name", values=["菜单"]),
        #    MessageMarkdownParams(key="message1", values=["欢迎来到幻想大陆！"]),
        #]
        #markdown = MarkdownPayload(custom_template_id="102057736_1726848614", params=params)

        #await message._api.post_group_message(
        #    group_openid=message.group_openid,
        #    msg_type=2, 
        #    msg_id=message.id,
        #    msg_seq=1,
        #    markdown=markdown
        #)
        txt = "\n❤❤欢迎来到幻想次元❤❤\n————————————————\n【➤➤➤指令菜单★★★】\n————————————————\n◈[属性]查看属性面板\n◈[背包]查看背包物品\n➥[使用 物品名*数量]使用背包物品\n◈[技能]查看已有技能\n➥[设置技能x 技能名]配置战斗技能\n◈[装备]查看身上装备\n➥[装备 装备名]穿戴背包装备\n◈[全局搜索 名称]搜索该物品信息\n————————————\n【制作功能】\n◈[制作列表]查看可制作物品\n➥[制作信息 物品名]查看物品制作信息\n➥[制作 物品名*数量]制作若干个物品\n————————————\n【队伍功能】\n◈[创建队伍]创建一支四人队伍\n➥[队伍列表]查看现有队伍\n➥[加入队伍x]加入一支队伍\n➥[退出队伍]退出已在队伍\n————————————\n【探索中】\n◈[开启自动战斗]\n➥[关闭自动战斗]\n◈[上][下][左][右]进行探索\n◈[休息]进行休战回血\n◈[使用 道具名*数量]使用若干道具\n————————————\n【战斗中】\n◈[战斗面板]查看对战双方状态\n◈[普攻]进行普通攻击\n◈[技能x]进行技能攻击\n◈[使用 道具名]使用单个道具\n◈[逃跑]尝试逃离战斗\n————————————\n【商店中】\n◈[购买 物品名*数量]购买商店物品\n◈[出售 物品名*数量]出售背包物品\n◈[离开商店]退出商店并继续探索\n————————————\n【交易功能】\n◈[赠送 ID*物品名*数量]赠送玩家物品\n➥[我]查看自身ID"
        await send_message(message, 0, 1, txt, "https://gss0.baidu.com/9fo3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/cb8065380cd791230d0a6aa2a8345982b3b7807a.jpg")
        return

 
    elif await txt_exist("player", "number", number, "") == "不存在" and "注册" not in message.content:

        txt = f"\n【请先完成注册哦！】\n◈示例:[注册 昵称]"
        await send_message(message, 0, 1, txt)
        return

    elif "祈祷" in message.content:

        await daily_wish(message)
        return

    elif "背包" in message.content:

        await my_bag(message)
        return

    elif message.content == "属性" or message.content == "我的属性" or message.content == "属性信息":

        await my_attribute(message)
        return

    elif message.content == "面板" or message.content == "我的面板" or message.content == "面板信息":

        await my_board(message)
        return

    elif message.content == "装备" or message.content == "我的装备" or message.content == "装备信息":

        await my_equip(message)
        return

    elif message.content == "技能" or message.content == "我的技能" or message.content == "技能信息":

        await my_skill(message)
        return
    
    elif message.content == "副职业" or message.content == "副职" or message.content == "职业":

        await my_job(message)
        return

    elif message.content == "任务" or message.content == "我的任务" or message.content == "任":

        await my_task(message)
        return

    elif message.content == "进化" or message.content == "进化面板" or message.content == "我的进化":

        await my_evolute(message)
        return


#我要注册        
    elif message.content[:2] == "注册":

        name = message.content.replace("注册", "").replace(" ", "")
        if name == "": 
            txt = f"【请输入完整的昵称】\n示例:[注册 小四]"

            await send_message(message, 0, 1, txt)
            return

        with open("data/player.txt", 'r') as f:
            data = json.load(f)
        for user in data:
            if user['number'] == number:
                nickname = user['nickname']
                txt = f"【[{nickname}]你已经注册过了哟！】"

                await send_message(message, 0, 1, txt)
                return
    
        else:
            # 如果不存在，则导入number的用户数据
            new_id = len(data) + 1
            x = random.randint(50, 250)
            y = random.randint(-260, -240)
            new_user = {'id': new_id, 'number': number, 'nickname': name, '状态': "否", "x": x, "y": y, "地名": "幽暗密林", "队伍中": "否"}
            data.append(new_user)
            nickname = new_user['nickname']
            # 将数据写入玩家列表
            with open("data/player.txt", 'w') as f:
                json.dump(data, f, ensure_ascii=False, indent=4)
            new_users = {'id': new_id, 'number': number, 'nickname': name, "属性点": 0, "力量": {"基础": 0, "躯体": 0, "加点": 0, "装备": 0, "进化": 0, "加成": 0, "最终": 0}, "智力": {"基础": 0, "躯体": 0, "加点": 0, "装备": 0, "进化": 0, "加成": 0, "最终": 0}, "体质": {"基础": 0, "躯体": 0, "加点": 0, "装备": 0, "进化": 0, "加成": 0, "最终": 0}, "敏捷": {"基础": 0, "躯体": 0, "加点": 0, "装备": 0, "进化": 0, "加成": 0, "最终": 0}, "体魄":[], "血脉":[], "天赋":[], "等级": 0, "经验": {"最大": 1, "当前": 0}, "生命": {"基础最大": 0, "加成": 0, "最终": 0, "当前最大": 0, "当前": 0}, "魔力": {"基础最大": 0, "加成": 0, "最终": 0, "当前最大": 0, "当前": 0}, "物攻": {"基础": 0, "加成": 0, "最终": 0, "当前": 0}, "魔攻": {"基础": 0, "加成": 0, "最终": 0, "当前": 0}, "物防": {"基础": 0, "加成": 0, "最终": 0, "当前": 0}, "魔防": {"基础": 0, "加成": 0, "最终": 0, "当前": 0}, "命中": {"基础": 0, "加成": 0, "最终": 0, "当前": 0}, "闪避": {"基础": 0, "加成": 0, "最终": 0, "当前": 0}, "暴击": {"基础": 0, "加成": 0, "最终": 0, "当前": 0}, "暴免": {"基础": 0, "加成": 0, "最终": 0, "当前": 0}, "暴伤": {"基础": 0, "加成": 0, "最终": 0, "当前": 0}, "暴抗": {"基础": 0, "加成": 0, "最终": 0, "当前": 0}, "韧性": {"基础": 0, "加成": 0, "最终": 0, "当前": 0}, "速度": {"基础": 0, "加成": 0, "最终": 0, "当前": 0}, "生命回复": 0, "魔力回复": 0, "物理增伤": 0, "魔法增伤": 0, "物理减伤": 0, "魔法减伤": 0, "物理穿透": 0, "魔法穿透": 0, "最低命中率": 0, "最低闪避率": 0, "最低暴击率": 0, "装备技能": {"数量": 1, "技能1": "", "技能2": "", "技能3": "", "技能4": "", "技能5": "", "技能6": "", "技能7": "", "技能8": "", "技能9": "", "技能10": ""}, "学会技能": [], "特殊效果": [], "体力": 50, "每日任务记录": {}, "剧情任务记录": {}, "赠送限制": {"总额度": 0, "分额度": {}}, "好感度": {}, "副职业": []}
            new_bag = {"id": new_id, "number": number, "nickname": name, "装备":{"武器": "木棍", "副手": "", "头肩": "", "上身": "", "腰部": "", "下身": "", "脚部": "", "项链": "", "手镯": "", "戒指": ""}, "背包": []}
            #创建玩家独立信息
            if not os.path.exists(f"player/{new_id}.txt"):
                with open(f"data/player/{new_id}.txt", 'w', encoding='utf-8') as f:
                   json.dump(new_users, f, ensure_ascii=False)
            #创建玩家独立背包 
            if not os.path.exists(f"bag/{new_id}.txt"):
                with open(f"data/bag/{new_id}.txt", 'w', encoding='utf-8') as f:
                   json.dump(new_bag, f, ensure_ascii=False)

        txt = "【注册成功！】\n————你被次元之门吞噬————\n......\n......\n......\n————伸手不见五指————\n......\n......\n......\n一道斑斓色划过你的面前，你听到了一阵陌生的声音\n......\n......\n......\n【指引】发送[细听]"

        await send_message(message, 0, 1, txt)
        return

#注册分配加点   
    elif message.content == "细听":

        if state == "否":
            txt = await txt_write("player", "number", number, "状态", "进行中")
            txt = f"\n一阵虚弱的声音在耳畔缭绕\n“来自异次元的行者啊”\n“来此尽管是不是你本意，可我别无选择”\n“你将莅此完成你的使命”\n“此处为幻想大陆，本应是个美好之地，族群和睦相处”\n周围似乎回荡着幽幽的叹息\n“可近年来风起云涌，灾祸不断，局势愈加扑朔诡谲”\n“我有预感，这是毁灭的前兆”\n“愿命定的你向前劈开迷雾，消灭灾厄，拯救世间”\n“我将以神力赐予你新的躯体，助你更好的适应新环境”\n强烈的七彩光芒将你笼罩，你感觉强大的生机注入体内\n“愿你一路顺风”\n————————————\n请为新躯体分配属性：\n◇力量(0)◇\n◇智力(0)◇\n◇体质(0)◇\n◇敏捷(0)◇\n共 20 点，已分配 0 点\n【指引】示例：[力量5智力5体质5敏捷5]"

            await send_message(message, 0, 1, txt)
            return

#注册分配加点
    elif state == "进行中":

        stats = {"力量": 0, "智力": 0, "体质": 0, "敏捷": 0}
        pattern = r"(力量|智力|体质|敏捷)(\d+)"
        matches = re.findall(pattern, message.content)
        if len(matches) == 4:
            for stat in matches:
                if len(stat) > 2:
                    txt = f"\n格式不正确！\n请为新躯体分配属性：\n◇力量(0)◇\n◇智力(0)◇\n◇体质(0)◇\n◇敏捷(0)◇\n共 20 点，已分配 0 点\n示例：[力量5智力5体质5敏捷5]"

                    await send_message(message, 0, 1, txt)
                    return

            total = sum(int(num) for stat, num in matches)
            if total != 20:
                txt = f"分配总和不等于20！\n请为新躯体分配属性：\n◇力量(0)◇\n◇智力(0)◇\n◇体质(0)◇\n◇敏捷(0)◇\n共 20 点，已分配 0 点\n示例：[力量5智力5体质5敏捷5]"

                await send_message(message, 0, 1, txt)
                return

            for stat, num in matches:
                stats[stat] = int(num)
            with open("data/body.txt", 'r') as f:
                data = json.load(f)
            body = []
            blood = []
            talent = []
            random.seed(time.time())
            for item in data:
                if item["种类"] == "体质":
                    ran = 0.8 * pow(0.5, len(body))
                    if "小于" in item["需求"]: 
                        if int(stats[item["需求"][2:4]]) <= int(item["需求"][4:]):
                            if random.random() < ran:
                                body.append(item["名称"])
                    if "大于" in item["需求"]:
                        if int(stats[item["需求"][2:4]]) >= int(item["需求"][4:]):
                            if random.random() < ran:
                                body.append(item["名称"])
                elif item["种类"] == "血脉":
                    ran = 0.25 * pow(0.4, len(blood))
                    requirements = item["需求"].split(" ")
                    if all(int(requirement[2:]) <= stats[requirement[:2]] for requirement in requirements):
                        if random.random() < ran and len(blood) < 2:
                            blood.append(item["名称"])
                elif item["种类"] == "天赋" and int(stats[item["需求"][:2]]) >= int(item["需求"][2:]):
                    ran = 0.01 * pow(0.1, len(talent))
                    if random.random() < ran:
                        talent.append(item["名称"])
            with open("data/player.txt", 'r') as f:
                data = json.load(f)
            for item in data:
                if item.get("number") == number:

                    #修改这里进行反复分配测试 进入世界（进行中）

                    item["状态"] = "进入世界"
                    id = item["id"]
                    with open("data/player.txt", 'w') as f:
                        json.dump(data, f, ensure_ascii=False, indent=4)
                    break

            with open(f"data/player/{id}.txt", 'r') as f:
                item = json.load(f)
                item["力量"]["基础"] = stats["力量"]
                item["智力"]["基础"] = stats["智力"]
                item["体质"]["基础"] = stats["体质"]
                item["敏捷"]["基础"] = stats["敏捷"]
                item["体魄"] = body
                item["血脉"] = blood
                item["天赋"] = talent
                with open(f"data/player/{id}.txt", 'w') as f:
                    json.dump(item, f, ensure_ascii=False, indent=4)

            #属性计算刷新
            await attribute_count(message)

            #回满血蓝
            with open(f"data/player/{id}.txt", 'r') as f:
                item = json.load(f)
                item["生命"]["当前最大"] = item["生命"]["最终"]
                item["魔力"]["当前最大"] = item["魔力"]["最终"]
                item["生命"]["当前"] = item["生命"]["最终"]
                item["魔力"]["当前"] = item["魔力"]["最终"]
                item["物攻"]["当前"] = item["物攻"]["最终"]
                item["魔攻"]["当前"] = item["魔攻"]["最终"]
                item["物防"]["当前"] = item["物防"]["最终"]
                item["魔防"]["当前"] = item["魔防"]["最终"]
                item["命中"]["当前"] = item["命中"]["最终"]
                item["闪避"]["当前"] = item["闪避"]["最终"]
                item["暴击"]["当前"] = item["暴击"]["最终"]
                item["暴免"]["当前"] = item["暴免"]["最终"]
                item["暴伤"]["当前"] = item["暴伤"]["最终"]
                item["暴抗"]["当前"] = item["暴抗"]["最终"]
                item["韧性"]["当前"] = item["韧性"]["最终"]
                item["速度"]["当前"] = item["速度"]["最终"]
                with open(f"data/player/{id}.txt", 'w') as f:
                    json.dump(item, f, ensure_ascii=False, indent=4)

            if len(body) != 0:
                body_txt = "【" + "】\n【".join(body) + "】"
            else:
                body_txt = "【无】"
            if len(blood) != 0:
                blood_txt = "【" + "】\n【".join(blood) + "】"
            else:
                blood_txt = "【无】"
            if len(talent) != 0:
                talent_txt = "【" + "】\n【".join(talent) + "】"
            else:
                talent_txt = "【无】"
            txt = f"\n重塑躯体成功！\n(测试中)\n你的体魄为\n{body_txt}\n你的血脉为\n{blood_txt}\n你的天赋为\n{talent_txt}\n————————————\n欢迎来到  幻想大陆！\n【指引】发送[进入世界]"

            await send_message(message, 0, 1, txt)
            return

        else:
            txt = f"\n请先完成当前操作！\n请为新躯体分配属性：\n◇力量(0)◇\n◇智力(0)◇\n◇体质(0)◇\n◇敏捷(0)◇\n共 20 点，已分配 0 点\n示例：[力量5智力5体力5敏捷5]"

            await send_message(message, 0, 1, txt)
            return



#以下为新手教程       

    elif state == "进入世界":

        if message.content != "进入世界":
            txt = f"请先跟着教程操作哟！\n发送[进入世界]"

            await send_message(message, 0, 1, txt)
            return

        else:
            await txt_write("player", "number", number, "状态", "教程1")
            txt = f"\n一阵天旋地转，周围的黑色褪去，葱茏的绿意将你笼罩。\n一棵树，两棵树，数不胜数的树木，一望无际的树丛。\n你正身处一片森林之中。\n远日西斜，此时已近黄昏，天空隐约渗着一丝血红。\n树木阴影交错，随风摇曳，一阵鸦鸣自远方传来，久久回荡。\n你检查了下身上，却是空无一物。\n你捡起一段看上去还算结实的木棍，颤巍巍的向着一个方向摸索而去。\n————————————\n【指引】发送[上][下][左][右]进行探索"

            await send_message(message, 0, 1, txt)
            return

    elif state == "教程1": 

        if message.content != "上" and message.content != "下" and message.content != "左" and message.content != "右":
            txt = f"请先跟着教程操作哟！\n发送[上][下][左][右]进行探索"

            await send_message(message, 0, 1, txt)
            return

        else:
            await battle_initialization("哥布林", 1, message, "羸弱")
            await txt_write("player", "number", number, "状态", "教程2")
            txt = f"◈你在昏暗中向前摸索。\n◈许久，朦朦胧胧看见了一丝光亮。\n◈你小心翼翼的靠近，发现是一座山洞，里面正燃着一个火堆。\n◈一个绿色的生物正坐在火堆前大快朵颐，散发出一股诱惑的肉香。\n◈饿了半天的你终究还是忍不住，偷偷摸摸的往前凑去。\n◈你刚摸到洞口，一只乌鸦从边上草丛啪嗒啪嗒的飞起，发出了不小的动静。\n◈火堆前的那个生物有所惊觉，倏然扭过了头，那是一张狰狞的绿脸。\n◈他飞快的站起，抄起地上的一根骨棒，向你飞扑而来。\n————————————\n★进入战斗★\n◇战斗信息◇\n◇普攻◇\n◇技能◇\n◇道具◇\n◇逃跑◇\n【指引】发送[战斗面板]查看对面信息"

            await send_message(message, 0, 1, txt)
            return

    elif state == "教程2": 
        if message.content != "战斗面板":
            txt = f"◈请先跟着教程操作哟！\n◈发送[战斗面板]查看对战信息"

            await send_message(message, 0, 1, txt)
            return

        elif message.content == "战斗面板":
            await battle_view(message)
            txt1 = "\n◈发送[普攻]看看吧"
            await txt_write("player", "number", number, "状态", "教程3")

            await send_message(message, 1, 5, txt1)
            return

    elif state == "教程3":

        if message.content != "普攻":

            txt = f"◈请先跟着教程操作哟！\n◈发送[普攻]进行攻击"

            await send_message(message, 0, 5, txt)
            return

        elif message.content == "普攻":

            await battle_round(message)
            id = await player_id(number)
            with open(f"data/player/{id}.txt", 'r') as f:
                data = json.load(f)
                data["装备技能"]["技能1"] = "重击"
                data["学会技能"].append({"名称": "重击", "等级": 1})
                with open(f"data/player/{id}.txt", 'w') as f:
                    json.dump(data, f, ensure_ascii=False, indent=4)
            with open(f"data/battle/{id}.txt", 'r') as f:
                data = json.load(f)
                data["玩家"][0]["技能"].append({"名称": "重击", "等级": 1})
                with open(f"data/battle/{id}.txt", 'w') as f:
                    json.dump(data, f, ensure_ascii=False, indent=4)
            txt = "\n☪灵光一闪，你在战斗中有所顿悟，学会技能[重击]！\n◈【指引】发送[技能1]看看吧"
            await txt_write("player", "number", number, "状态", "教程4")

            await send_message(message, 1, 5, txt)
            return

    elif state == "教程4":
        
        if message.content != "技能1":

            txt = f"◈请先跟着教程操作哟！\n◈发送[技能1]进行技能攻击"

            await send_message(message, 0, 5, txt)
            return

        elif message.content == "技能1":

            await battle_round(message)
            txt = "\n✔就是这样！\n✔来取得第一场战斗的胜利吧！\n————————————\n◈当前目标：击杀哥布林\n◈发送[普攻]进行普通攻击\n◈发送[技能1]进行技能攻击\n◈发送[战斗面板]查看战斗信息"
            await txt_write("player", "number", number, "状态", "教程5")

            await send_message(message, 1, 5, txt)
            return

    elif state == "教程5":

        if message.content == "技能1" or message.content == "普攻":

            txt_return = await battle_round(message)
            if txt_return:
                await send_message(message, 0, 1, txt_return)
            return

        elif message.content == "战斗面板":

            await battle_view(message)
            return

        else:

            txt = f"\n◈当前目标：击杀哥布林\n◈发送[普攻]进行普通攻击\n◈发送[技能1]进行技能攻击\n◈发送[战斗面板]查看战斗信息"

            return

    elif "炼金师列表" in message.content or "分解师列表" in message.content or "锻造师列表" in message.content:

        await work_player_list(message)
        return

    elif message.content == "队伍列表":

        await team_list(message)
        return

    elif message.content == "队伍信息":

        await team_infor(message)
        return

    elif "制作列表" in message.content:
        await make_list(message)
        return

    elif "制作信息" in message.content:
        await make_infor(message)
        return
    
    elif "拍卖" in message.content:

        if not hasattr(message, 'group_openid'):
            txt = "【请在】"
            await send_message(message, 0, 5, txt)
            return

    elif state == "打工":
        
        if message.content != "结束打工":
            
            start_time = int(await player_read(number, "打工信息", "打工时间"))
            end_time = int(time.time())
            work_time = end_time - start_time
            days = work_time // 86400  # 计算天数
            hours = (work_time % 86400) // 3600  # 计算小时数
            minutes = (work_time % 3600) // 60  # 计算分钟数
            txt = "\n【你正在打工中，请不要偷懒哦！】\n【已打工{}天{}时{}分】\n◈发送[结束打工]结束\n【提醒】若打工时间不满1小时，不会有任何奖励，甚至会降低老板好感度！".format(days, hours, minutes)
            await send_message(message, 0, 1, txt)
            return

        else:

            await worldtree_action(message)
            return

    elif "验证码" in state:

        with open(f"data/player.txt", 'r') as f:
            data = json.load(f)
        for item in data:
            if item.get("number") == number:
                day_reward = int(item.get("验证码日次数",0))
                item["验证码日次数"] = day_reward + 1
                break
        reward_percent = 100 * (0.5 ** day_reward)
        verify_num = state.split("验证码")[1]
        code = verify_num.split("*")[0]
        count = int(verify_num.split("*")[1])
        folder_name = '验证码'
        file_name = '{}.png'.format(uid)
        # 拼接文件夹路径和文件名
        file_path = os.path.join(folder_name, file_name)
        reward_ran = random.uniform(0, 100)
        if message.content == code:
            if count == 0 and reward_ran < reward_percent:
                if random.random() < 0.03:
                    reward = "闪耀的鲜能剂"
                elif random.random() < 0.1:
                    reward = "大份鲜能剂"
                elif random.random() < 0.8:
                    reward = "鲜能剂"
                elif random.random() < 0.99:
                    reward = "天空碎片"
                else:
                    reward = "天空晶石"
                txt = "\n【世界向你播撒了眷顾——】\n◈获得[{}]×1".format(reward)
                await bag_add(uid, reward, 1)
                with open(f"data/player.txt", 'w') as f:
                    json.dump(data, f, ensure_ascii=False, indent=4)
                await txt_write("player", "number", number, "状态", "行动")
                os.remove(file_path)
                await send_message(message, 0, 1, txt)
                return
            elif count == 1 and reward_ran < reward_percent:
                if random.random() < 0.01:
                    reward = "闪耀的鲜能剂"
                elif random.random() < 0.03:
                    reward = "大份鲜能剂"
                elif random.random() < 0.2:
                    reward = "鲜能剂"
                elif random.random() < 0.95:
                    reward = "天空粉尘"
                else:
                    reward = "天空碎片"
                txt = "\n【世界发出微微的叹息——】\n◈获得[{}]×1".format(reward)
                await bag_add(uid, reward, 1)
                with open(f"data/player.txt", 'w') as f:
                    json.dump(data, f, ensure_ascii=False, indent=4)
                await txt_write("player", "number", number, "状态", "行动")
                os.remove(file_path)
                await send_message(message, 0, 1, txt)
                return
            else:
                txt = "\n【世界没有任何回应。。。】"
                await txt_write("player", "number", number, "状态", "行动")
                os.remove(file_path)
                await send_message(message, 0, 1, txt)
                return
        count += 1
        await txt_write("player", "number", number, "状态", "验证码{}*{}".format(code, count))
        with open(file_path, "rb") as f:
            image_data = f.read()
        # 将图片数据编码为 base64 字符串
        base64_data = base64.b64encode(image_data).decode("utf-8")
        _log = logging.get_logger()
        if hasattr(message, 'group_openid'):
            media_0 = await message._api.post_group_file(
            group_openid=message.group_openid,
            file_type=1,
            url=None,
            srv_send_msg=False,
            file_data=base64_data
            )
            messageResult = await message._api.post_group_message(
            group_openid=message.group_openid,
            msg_type=7, 
            msg_id=message.id,
            msg_seq=1,
            content="\n【你听闻世界的低语】\n【请做出回应：】",
            media=media_0
            )
            _log.info(messageResult)

        else:
            media_0 = await message._api.post_c2c_file(
            openid=message.author.user_openid,
            file_type=1,
            url=None,
            srv_send_msg=False,
            file_data=base64_data
            )
            messageResult = await message._api.post_c2c_message(
            openid=message.author.user_openid, 
            msg_type=7, 
            msg_id=message.id, 
            msg_seq=1,
            content="\n【你听闻世界的低语】\n【请做出回应：】",
            media=media_0
            )
            _log.info(messageResult)
        
        return

    elif "退出队伍" in message.content:

        await team_leave(message)
        return
    
    elif "传送" in message.content and "*" in message.content and "购买" not in message.content and "门" not in message.content:
        if "不够" in await bag_enough(uid, "便携式传送门", 1) and await txt_exist("player", "number", number, "地名") != "世界树24":
            txt = "\n【你不具备传送条件！】"
            await send_message(message, 0, 1, txt)
            return
        elif state != "行动" or await txt_exist("player", "number", number, "队伍中") != "否":
            txt = "\n【请先脱战并脱离队伍哦！】"
            await send_message(message, 0, 1, txt)
            return
        else: 
            xy = str(message.content.split("传送")[1])
            x = int(xy.split("*")[0])
            y = int(xy.split("*")[1])
            with open(f"data/map/坐标总览.txt", 'r') as f:
                data = json.load(f)
            place = "未知之地"
            for location in data:
                for coordinate in location['坐标']:
                    if int(coordinate['x1']) <= x <= int(coordinate['x2']) and int(coordinate['y1']) <= y <= int(coordinate['y2']):
                        place = location['名称']
                        break
            if await txt_exist("player", "number", number, "地名") != "世界树24":
                await bag_reduce(uid, "便携式传送门", 1)
            else:
                if "不够" in await bag_enough(uid, "铜币", 200):
                    txt = "\n【世界树•中层•世界传送门】\n『传送门守卫』\n“请缴纳足够的[铜币]！”\n◈发送[0]返回"
                    await send_message(message, 0, 1, txt)
                    return
                await bag_reduce(uid, "铜币", 200)
            await txt_write("player", "number", number, "x", int(x))
            await txt_write("player", "number", number, "y", int(y))
            await txt_write("player", "number", number, "地名", place)
            txt = "\n【你传送至({},{}){}】".format(x, y, place)
            await send_message(message, 0, 1, txt)
            return


    elif state == "强制休息":

        last_time = int(await txt_exist("player", "number", number, "休息时间"))
        now_time = int(time.time())
        time1 = now_time - last_time
        time0 = await read_time("复活间隔")
        if number == "71DFEA7BBB6DFB39E7C2B7ABB3ABDDB8":
            time0 = 6
        if time1 < time0:
            need_time = time0 - time1
            minute, second = divmod(need_time, 60)
            txt = "\n【昏迷中，距离苏醒{}分{}秒】".format(minute, second)
        else:
            await player_write(number, "生命", "当前", math.ceil(await player_read(number, "生命", "当前最大") / 2))
            await player_write(number, "魔力", "当前", math.ceil(await player_read(number, "魔力", "当前最大") / 2))
            await txt_write("player", "number", number, "状态", "行动")
            txt = "\n【你从昏迷中苏醒，感觉全身无比酸痛】"
        await send_message(message, 0, 1, txt)
        return

    elif state == "休息":
        if if_team == "队员":
            txt = "\n【队伍休憩整备中zzZ】\n【请听从队长的安排哦！】\n◈[队伍列表]\n◈[退出队伍]"
            await send_message(message, 0, 1, txt)
            return
        if if_team == "队长":
            last_time = int(await txt_exist("player", "number", number, "休息时间"))
            now_time = int(time.time())
            time1 = now_time - last_time
            time0 = await read_time("休息间隔")
            if number == "71DFEA7BBB6DFB39E7C2B7ABB3ABDDB8":
                time0 = 6
            if time1 < time0:
                need_time = time0 - time1
                minute, second = divmod(need_time, 60)
                txt = "\n【队伍休憩整备中zzZ】\n◈距离整装待发{}分{}秒".format(minute, second)
            else:
                uid = await player_id(number)
                with open("data/team.txt", 'r') as f:
                    team = json.load(f)
                found = False
                for item in team:
                    if uid in item["成员"]:
                        found = True
                        break
                if found:
                    for uid in item["成员"]:
                        player_num = await player_number(uid)
                        await player_write(player_num, "生命", "当前", await player_read(player_num, "生命", "当前最大"))
                        await player_write(player_num, "魔力", "当前", await player_read(player_num, "魔力", "当前最大"))
                        await txt_write("player", "number", player_num, "状态", "行动")
                    txt = "\n【队伍全员容光焕发!】\n【准备出击！】"
            await send_message(message, 0, 1, txt)
            return
        elif if_team == "否":
            last_time = int(await txt_exist("player", "number", number, "休息时间"))
            now_time = int(time.time())
            time1 = now_time - last_time
            time0 = await read_time("休息间隔")
            if number == "71DFEA7BBB6DFB39E7C2B7ABB3ABDDB8":
                time0 = 6
            if time1 < time0:
                need_time = time0 - time1
                minute, second = divmod(need_time, 60)
                txt = "\n【休息中zzZ】\n◈距离整装待发{}分{}秒".format(minute, second)
            else:
                await player_write(number, "生命", "当前", await player_read(number, "生命", "当前最大"))
                await player_write(number, "魔力", "当前", await player_read(number, "魔力", "当前最大"))
                await txt_write("player", "number", number, "状态", "行动")
                txt = "\n【你醒来了！】\n【感觉全身充满了力量！】"
            await send_message(message, 0, 1, txt)
            return


    elif state == "行动":
        player_place = await txt_exist("player", "number", number, "地名")



        if message.content == "休息":
            if if_team == "队员":
                txt = "\n【请听从队长的安排哦！】\n◈[队伍列表]\n◈[退出队伍]"
                await send_message(message, 0, 1, txt)
                return
            elif if_team == "队长":
                uid = await player_id(number)
                with open("data/team.txt", 'r') as f:
                    team = json.load(f)
                found = False
                for item in team:
                    if uid in item["成员"]:
                        found = True
                        break
                if found:
                    for uid in item["成员"]:
                        player_num = await player_number(uid)
                        await txt_write("player", "number", player_num, "状态", "休息")
                        await txt_write("player", "number", player_num, "休息时间", int(time.time()))
                        txt = "\n【你的队伍开始了休憩zzZ】"
                        await send_message(message, 0, 1, txt)
                        return
            elif if_team == "否":
                await txt_write("player", "number", number, "状态", "休息")
                await txt_write("player", "number", number, "休息时间", int(time.time()))
                txt = "\n【你开始了小憩zzZ】"
                await send_message(message, 0, 1, txt)
                return


        if message.content == "上" or message.content == "下" or message.content == "左" or message.content == "右" or ((message.content == "1" or message.content == "2" or message.content == "0") and "世界树" not in player_place):
            
            if if_team == "队长":
                player_place_1 = await txt_exist("player", "number", number, "地名")
                uid = await player_id(number)
                with open("data/team.txt", 'r') as f:
                    team = json.load(f)
                found = False
                for item in team:
                    if uid in item["成员"]:
                        found = True
                        break
                if found:
                    for uid in item["成员"]:
                        player_num = await player_number(uid)
                        player_state = await txt_exist("player", "number", player_num, "状态")
                        player_place_2 = await txt_exist("player", "number", player_num, "地名")
                        if "破败教会" not in player_place_1 and player_place_1 != player_place_2:
                            txt = "\n【有队员不在当前区域哦！】"
                            await send_message(message, 0, 1, txt)
                            return
                        if player_state == "强制休息" or player_state == "休息":
                            txt = "\n【你的队员状态不是很好呢！】\n◈先去[休息]一会儿吧~"
                            await send_message(message, 0, 1, txt)
                            return
            elif if_team == "队员":
                txt = "\n【请听从队长的安排哦！】\n◈[队伍列表]\n◈[退出队伍]"
                await send_message(message, 0, 1, txt)
                return
            uid = await player_id(number)
            with open(f"data/player/{uid}.txt", 'r') as f:
                data = json.load(f)
            now_time = int(time.time())
            last_time = data.get("行动时间戳", 0)
            time1 = now_time - last_time
            time0 = await read_time("探索间隔")
            if number == "71DFEA7BBB6DFB39E7C2B7ABB3ABDDB8":
                time0 = 3
            if time1 < time0:
                need_time = time0 - time1
                minute, second = divmod(need_time, 60)
                txt = "\n【距离下次行动{}分{}秒】".format(minute, second)
                await send_message(message, 0, 1, txt)
                return
            else:
                
                if random.random() < 0.05:

                    code = await generate_code(4)
                    # 绘制验证码
                    fig, ax = plt.subplots()
                    text = ax.text(0.5, 0.5, code, fontsize=36, ha='center', va='center')
                    # 隐藏坐标轴并放大数字
                    ax.axis('off')
                    ax.set_ylim([-10, 10])
                    ax.set_xlim([-10, 10])
                    ax.set_aspect('equal')
                    text.set_fontsize(128)
                    # 在验证码图片上随机绘制一些线条
                    for i in range(5):
                        x1, y1 = -10, random.uniform(-10, 10)
                        x2, y2 = 10, random.uniform(-10, 10)
                        line = ax.plot([x1, x2], [y1, y2], color='black', linewidth=5, zorder=10)
                    for i in range(10):
                        colors = ['#' + ''.join([random.choice('0123456789ABCDEF') for j in range(6)]) for i in range(1)]
                        random_color = random.choice(colors)
                        x1, y1 = -10, random.uniform(-10, 10)
                        x2, y2 = 10, random.uniform(-10, 10)
                        line = ax.plot([x1, x2], [y1, y2], color=random_color, linewidth=5, zorder=10)
                    for i in range(5):
                        x1, y1 = random.uniform(-10, 10), 10
                        x2, y2 = random.uniform(-10, 10), -10
                        line = ax.plot([x1, x2], [y1, y2], color='black', linewidth=5, zorder=10)
                    for i in range(10):
                        colors = ['#' + ''.join([random.choice('0123456789ABCDEF') for j in range(6)]) for i in range(1)]
                        random_color = random.choice(colors)
                        x1, y1 = random.uniform(-10, 10), 10
                        x2, y2 = random.uniform(-10, 10), -10
                        line = ax.plot([x1, x2], [y1, y2], color=random_color, linewidth=5, zorder=10)
                    # 添加背景纹理
                    cmap_list = ['viridis', 'plasma', 'inferno', 'cividis', 'BrBG', 'RdBu', 'coolwarm', 'Accent', 'Paired', 'Set1', 'tab10', 'gist_earth', 'terrain', 'ocean', 'gist_stern']
                    random_cmap = random.choice(cmap_list)
                    cmap = plt.cm.get_cmap(random_cmap)
                    norm = mcolors.Normalize(vmin=0, vmax=1)
                    background = np.random.rand(100, 50)
                    ax.imshow(background, cmap=cmap, norm=norm, interpolation='nearest', aspect='auto', extent=[-10, 10, -10, 10], alpha=1)
                    await txt_write("player", "number", number, "状态", "验证码{}*0".format(code))
                    # 指定文件夹名称和文件名
                    folder_name = '验证码'
                    file_name = '{}.png'.format(uid)
                    # 拼接文件夹路径和文件名
                    file_path = os.path.join(folder_name, file_name)
                    # 如果文件夹不存在，则创建文件夹
                    if not os.path.exists(folder_name):
                        os.makedirs(folder_name)
                    # 如果同名文件已存在，则删除同名文件
                    if os.path.exists(file_path):
                        os.remove(file_path)
                    # 保存图片到指定文件夹下，覆盖同名文件
                    plt.savefig(file_path)
                    with open(file_path, "rb") as f:
                        image_data = f.read()
                    # 将图片数据编码为 base64 字符串
                    base64_data = base64.b64encode(image_data).decode("utf-8")
                    _log = logging.get_logger()
                    if hasattr(message, 'group_openid'):
                        media_0 = await message._api.post_group_file(
                        group_openid=message.group_openid,
                        file_type=1,
                        url=None,
                        srv_send_msg=False,
                        file_data=base64_data
                        )
                        messageResult = await message._api.post_group_message(
                        group_openid=message.group_openid,
                        msg_type=7, 
                        msg_id=message.id,
                        msg_seq=1,
                        content="\n【你听闻世界的低语】\n【请做出回应：】",
                        media=media_0
                        )
                        _log.info(messageResult)

                    else:
                        media_0 = await message._api.post_c2c_file(
                        openid=message.author.user_openid,
                        file_type=1,
                        url=None,
                        srv_send_msg=False,
                        file_data=base64_data
                        )
                        messageResult = await message._api.post_c2c_message(
                        openid=message.author.user_openid, 
                        msg_type=7, 
                        msg_id=message.id, 
                        msg_seq=1,
                        content="\n【你听闻世界的低语】\n【请做出回应：】",
                        media=media_0
                        )
                        _log.info(messageResult)

                    return



                data["行动时间戳"] = now_time
                with open(f"data/player/{uid}.txt", 'w') as f:
                    json.dump(data, f, ensure_ascii=False, indent=4)
                await move(message)
                return
            return

        elif message.content == "开启自动战斗":

            uid = await player_id(number)
            with open(f"data/player/{uid}.txt", 'r') as f:
                data = json.load(f)
                data["自动战斗"] = "是"
            with open(f"data/player/{uid}.txt", 'w') as f:
                json.dump(data, f, ensure_ascii=False, indent=4)
            txt = "\n【你开启了自动战斗！】\n◈[设置自动战斗x-x-x]设置技能顺序，0为普攻\n 示例：[设置自动战斗1-0-1]"
            await send_message(message, 0, 1, txt)
            return

        elif message.content == "关闭自动战斗":

            uid = await player_id(number)
            with open(f"data/player/{uid}.txt", 'r') as f:
                data = json.load(f)
                data["自动战斗"] = "否"
            with open(f"data/player/{uid}.txt", 'w') as f:
                json.dump(data, f, ensure_ascii=False, indent=4)
            txt = "\n【你关闭了自动战斗！】"
            await send_message(message, 0, 1, txt)
            return

        elif "设置自动战斗" in message.content:

            skill = message.content.replace("设置自动战斗", "")
            uid = await player_id(number)
            with open(f"data/player/{uid}.txt", 'r') as f:
                data = json.load(f)
                data["自动战斗顺序"] = skill
            with open(f"data/player/{uid}.txt", 'w') as f:
                json.dump(data, f, ensure_ascii=False, indent=4)
            txt = "\n【目前自动战斗技能顺序为{}！】".format(skill)
            await send_message(message, 0, 1, txt)
            return
            
        elif "设置技能" in message.content:

            match1 = re.search(r"设置技能(\d+)", message.content)
            if match1:
                skill_num = int(match1.group(1))
            else:
                txt = "\n【输入格式错误！】"
                await send_message(message, 0, 1, txt)
                return
            match2 = re.search(r"\d+(.+)", message.content)
            if match2:
                skill_name = match2.group(1)
            else:
                txt = "\n【输入格式错误！】"
                await send_message(message, 0, 1, txt)
                return

            uid = await player_id(number)
            with open(f"data/player/{uid}.txt", 'r') as f:
                data = json.load(f)
            if skill_num <= int(data["装备技能"]["数量"]):
                skill_num_word = "技能" + str(skill_num)
                data["装备技能"][skill_num_word] = skill_name
                with open(f"data/player/{uid}.txt", 'w') as f:
                    json.dump(data, f, ensure_ascii=False, indent=4)
                txt = "\n【设置了{}为[{}]】".format(skill_num_word, skill_name)
            else:
                txt = "\n【设置序号错误！目前只能携带[{}]个技能】".format(data["装备技能"]["数量"])
            await send_message(message, 0, 1, txt)
            return


        
        elif "属性分配" in message.content:

            await devide_attribute(message)
            return

        elif "装备" in message.content:

            await equip(message)
            return

        elif "队伍" in message.content:

            if message.content == "创建队伍":
        
                await team_create(message)
                return

            elif "加入队伍" in message.content:

                await team_join(message)
                return

            elif "退出队伍" in message.content:

                await team_leave(message)
                return


        elif "使用" in message.content:

            await action_use(message)
            return 

        elif "制作" in message.content:

            await make_thing(message)
            return
        
        elif "分解" in message.content:

            if "委托" in message.content:
                await help_resolve_thing(message)
                return

            await resolve_thing(message)
            return

        elif "附魔" in message.content:
                
                if "委托" in message.content:
                    await help_do_enchant(message)
                    return

                await do_enchant(message)
                return

        elif "强化" in message.content:

                await do_reinforce(message)
                return

        elif "炼金" in message.content:
            
            if "委托" in message.content:
                
                await help_do_alchemy(message)
                return

            if "批量炼金" not in message.content:

                await do_alchemy(message)
                return

            else:

                await do_many_alchemy(message)
                return
        
        elif "宠物" in message.content:
            
            if  "宠物信息" in message.content:
                await pet_information(message)
                return

            if  "宠物突破" in message.content:
                await pet_break(message)
                return 

        elif "世界树" in player_place:
          
            await worldtree_action(message)
            return   
        



    elif state == "战斗": 
        uid = await player_id(number)
        if message.content == "战斗面板" or message.content == "面板":

            await battle_view(message)
            return

        elif message.content == "普攻" or "技能" in message.content or "使用" in message.content:
            if "使用" in message.content:

                use_thing = message.content.split("使用")[1]
                can_use = ["小血瓶", "中血瓶", "大血瓶", "小魔瓶", "中魔瓶", "大魔瓶", "草莓", "蓝莓", "天罚符咒", "闪亮的祝福"]
                if use_thing not in can_use:
                    txt_return = "\n【[{}]不是战斗中可使用的物品！】".format(use_thing)
                    await send_message(message, 0, 1, txt_return)
                    return
                if "不够" in await bag_enough(uid, use_thing, 1):
                    txt_return = "\n【你没有足够的[{}]！】".format(use_thing)
                    await send_message(message, 0, 1, txt_return)
                    return

            if "技能" in message.content:
                skill_number = message.content.split("技能")[1]
                try:
                    skill_number = int(skill_number)
                    skill_max = int(await player_read(number, "装备技能", "数量"))
                    if skill_number > skill_max:
                        txt_return = "\n【技能指令错误！】"
                        await send_message(message, 0, 1, txt_return)
                        return
                except ValueError:
                    txt_return = "\n【技能指令错误！】"
                    await send_message(message, 0, 1, txt_return)
                    return
        


            txt_return = await battle_round(message)
            if txt_return:
                await send_message(message, 0, 1, txt_return)
            return
        


        elif message.content == "逃跑":
            with open("data/team.txt", 'r') as f:
                team = json.load(f)
            found = False
            for item in team:
                if uid in item["成员"]:
                    if item["成员"][0] != uid:
                        txt = "\n【你不是队长！】"
                        await send_message(message, 0, 1, txt)
                        return
                    else:
                        battle_id = uid
                        found = True
                        break
            if not found:
                battle_id = await player_id(number)
                
            with open(f"data/battle/{battle_id}.txt", 'r') as f:
                battle_data = json.load(f)
            for team_player in battle_data["玩家"]:
                in_player_number = await player_number(team_player["uid"])
                hp_reduce = team_player["生命"]["当前"] / 50
                mp_reduce = team_player["魔力"]["当前"] / 50
                if hp_reduce > team_player["生命"]["当前最大"] / 100:
                    hp_reduce = team_player["生命"]["当前最大"] / 100
                if mp_reduce > team_player["魔力"]["当前最大"] / 100:
                    mp_reduce = team_player["魔力"]["当前最大"] / 100
                await player_write(in_player_number, "生命", "当前", int(team_player["生命"]["当前"] - hp_reduce))
                await player_write(in_player_number, "魔力", "当前", int(team_player["魔力"]["当前"] - mp_reduce))
                await txt_write("player", "number", in_player_number, "状态", "行动")

            os.remove(f"data/battle/{battle_id}.txt")
            txt = "\n【你落荒而逃，狼狈不堪！】"

            await send_message(message, 0, 1, txt)
            return

        else:
            txt = "\n【你正在战斗中！】\n◈发送[战斗面板]查看信息"

            await send_message(message, 0, 1, txt)
            return


    elif state == "野外商店" or state == "野外神秘商店" or state == "公会商店" or state == "世界树商店":

        if state == "公会商店":
            
            if "购买" in message.content:
                
                await guild_shop_buy(message)
                return

            if "公会商店" in message.content:
                
                await guild_shop(message)
                return

            if "离开商店" in message.content:

                await txt_write("player", "number", number, "状态", "行动")
                txt = "\n『吉祥物·猫猫』\n(灬ºωº灬)\n“冒险家大人要常来哦~”\n“猫猫会想念你的！”"
                await send_message(message, 0, 1, txt)
                return

        if "购买" in message.content and state != "公会商店":
            
                await shop_buy(message)
                return

        elif "出售" in message.content:

            await shop_sell(message)
            return

        elif "离开商店" in message.content:

            await txt_write("player", "number", number, "状态", "行动")
            txt = "\n【你离开了商店。。。】"
            await send_message(message, 0, 1, txt)
            return
        else:
            txt = "\n【你正在购物中！】\n◈发送[离开商店]离开"
            await send_message(message, 0, 1, txt)
            return
        




 

